package com.tarena.lbs.activity.controller;

import com.tarena.lbs.activity.pojo.param.ActivityAddParam;
import com.tarena.lbs.activity.pojo.param.ActivityStatusParam;
import com.tarena.lbs.activity.pojo.query.ActivityQuery;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.activity.service.ActivityService;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 活动相关功能接口
 */
@RestController
@Tag(name = "活动服务", description = "活动服务")
@Slf4j
public class ActivityController {

    @Autowired
    private ActivityService activityService;


    /**
     * 分页查询商家活动列表
     *
     * @return 分页结果，包含活动信息列表
     * @throws BusinessException 业务异常
     */
    @Operation(summary = "商家活动列表")
    @PostMapping("/admin/marketing/marketingActivity/info/list")
    @Validated
    public Result<PageResult<ActivityVO>> pageList(@RequestBody ActivityQuery query)
            throws BusinessException {
        log.debug("[控制层]处理商家活动列表,入参{}", query);
        checkShopPermission();
        return new Result<>("0", "success", activityService.pageList(query));
    }

    /**
     * 保存商家活动信息
     *
     * @param param 活动添加参数对象
     * @return 操作结果
     * @throws BusinessException 业务异常
     */
    @Operation(summary = "商家活动保存")
    @PostMapping("/admin/marketing/marketingActivity/info/save")
    public Result<Void> activitySave(@RequestBody @Valid ActivityAddParam param)
            throws BusinessException {
        return handleActivityOperation(param, "保存", true);
    }

    /**
     * 编辑商家活动信息
     *
     * @param param 活动编辑参数对象
     * @return 操作结果
     * @throws BusinessException 业务异常
     */
    @Operation(summary = "商家活动编辑")
    @PostMapping("/admin/marketing/marketingActivity/info/update")
    public Result<Void> activityUpdate(@RequestBody @Valid ActivityAddParam param)
            throws BusinessException {
        return handleActivityOperation(param, "编辑", false);
    }

    /**
     * 查询商家活动详情
     *
     * @param id 活动ID
     * @return 活动详细信息
     * @throws BusinessException 业务异常
     */
    @Operation(summary = "商家活动详情")
    @GetMapping("/admin/marketing/marketingActivity/info/detail/{id}")
    public Result<ActivityVO> activityDetail(@PathVariable("id") @NotNull(message = "活动ID不能为空") Integer id)
            throws BusinessException {
        log.debug("[控制层]处理显示活动详情,入参{}", id);
        checkShopPermission();
        ActivityVO data = activityService.activityDetail(id);
        if (data == null) {
            return Result.fail("404", "活动不存在");
        }
        return new Result<>("0", "success", data);
    }


    /**
     * 更新活动状态（启用/禁用）
     *
     * @param param 活动状态更新参数对象
     * @return 操作结果
     * @throws BusinessException 业务异常
     */
    @Operation(summary = "更新活动状态")
    @PostMapping("/admin/marketing/marketingActivity/info/updateStatus")
    public Result<Void> updateActivityStatus(@RequestBody @Valid ActivityStatusParam param)
            throws BusinessException {
        log.debug("[控制层]处理更新活动状态,入参{}", param);
        checkShopPermission();

        if (param.getId() == null || param.getStatus() == null) {
            return Result.fail("403", "参数不完整");
        }
        // 调用服务层更新状态
        int rows = activityService.updateActivityStatus(param.getId(), param.getStatus());
        // 返回结果
        return (rows > 0) ? Result.success() : Result.fail("405", "活动不存在");
    }

    /**
     * 处理活动操作的通用方法（包括保存和编辑）
     *
     * @param param         活动操作参数对象
     * @param operationType 操作类型（如"保存"或"编辑"）
     * @param isSave        是否是新增操作
     * @return 操作结果
     * @throws BusinessException 业务异常
     */
    private Result<Void> handleActivityOperation(ActivityAddParam param, String operationType, boolean isSave)
            throws BusinessException {
        log.debug("[控制层]处理商家活动{},入参{}", operationType, param);
        checkShopPermission();

        if (param == null) {
            return Result.fail("400", "参数缺失");
        }

        int rows = activityService.activitySave(param);
        return (rows > 0) ? Result.success() : Result.fail("405", "操作失败");
    }

    /**
     * 公共鉴权方法
     */
    private void checkShopPermission() throws BusinessException {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        if (userPrinciple == null || userPrinciple.getRole() == null) {
            throw new BusinessException("401", "未登录");
        } else if (userPrinciple.getRole() != Roles.SHOP) {
            throw new BusinessException("402", "无权限");
        }
        log.debug("[控制层]处理商家活动鉴权成功");
        log.debug("当前用户信息{}", userPrinciple);
    }
}
